package com.example.cargroup.viewmodel;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.cargroup.R;
import com.example.cargroup.adapter.CarAdapter;
import com.example.cargroup.data.entity.CarEntity;
import com.example.cargroup.data.entity.SubCarEntity;
import com.example.cargroup.model.CarModel;
import com.example.mvvmcommon.arouterprovider.UserProvider;
import com.example.mvvmcommon.field.UIField;
import com.example.mvvmcommon.mvvm.viewmodel.BaseViewModel;
import com.example.networkmoudel.entity.BaseEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class
CarViewModel extends BaseViewModel<CarModel> implements OnItemChildClickListener {

    public CarAdapter carAdapter=new CarAdapter();
    public ObservableField<String>allPrice=new ObservableField<>("合计：￥0");
    public ObservableField<Boolean>allCheck=new ObservableField<>(false);
    public ObservableField<String>edtStr=new ObservableField<>("编辑");
    private float price = 0f;
    @Override
    protected void initData() {
        carAdapter.setOnItemChildClickListener(this);
        int id = ((UserProvider) ARouter.getInstance().build("/usergroup/userprovider").navigation()).getUserId();
        if (id == 0){
            //跳转到登录界面
            Map<String,Object>pageMap = new HashMap<>();
            pageMap.put(UIField.ACTIONTYPE,UIField.AROUTERSTART);
            pageMap.put(UIField.ACTIONROUTERKEY,"/user/login");
            getUiChangeLiveData().getStartActivity().setValue(pageMap);
        }
        Map<String,Object>map=new HashMap<>();
        map.put("id",id);
        m.requestCar(map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);

    }

    @Override
    protected CarModel createModel() {
        return new CarModel();
    }

    @Override
    protected void sucessFull(BaseEntity entity) {
        if (entity instanceof CarEntity) {
            CarEntity entity1 = (CarEntity) entity;
//            LogUtils.json(entity1);
            carAdapter.setNewInstance(entity1.getData());
            checkPrice();
        } else if (entity instanceof SubCarEntity) {
            SubCarEntity subCarEntity = (SubCarEntity) entity;
            if (subCarEntity.getMessage().equals("购物车提交成功")) {
                int orderId = subCarEntity.data;
                Bundle bundle = new Bundle();
                bundle.putInt("orderId", orderId);
                Map<String, Object> map = new HashMap<>();
                map.put(UIField.ACTIONTYPE, UIField.AROUTERSTART);
                map.put(UIField.VALUESKEY, bundle);
                map.put(UIField.ACTIONROUTERKEY, "/cargroup/confirmorderactivity");
                getUiChangeLiveData().getStartActivity().setValue(map);
            }

        }
    }

    public void finish(){
        getUiChangeLiveData().getFinishActivity().setValue(""+System.currentTimeMillis());
    }

    //计算全部选中数据金额方法
    private void checkPrice(){
        List<CarEntity.DataBean> list = carAdapter.getData();
        if (list.size()==0){
            allPrice.set("合计：￥0");
            return;
        }
        price=0f;
        boolean flag=true;
        for (CarEntity.DataBean dataBean:list) {
            if (dataBean.selFalg){
                price+=(Float.valueOf(dataBean.getGoods_price())*dataBean.getGoods_count());
            }else {
                flag=false;
            }
        }
        allPrice.set("合计：￥"+price);
        allCheck.set(flag);

    }

    //编辑按钮点击监听
    public void edtChickListener(){
        List<CarEntity.DataBean> list = carAdapter.getData();
        if (list.size()==0)
            return;
        List<CarEntity.DataBean>dataBeans=new ArrayList<>();
        for(CarEntity.DataBean dataBean:list){
            dataBean.edtFlag=!dataBean.edtFlag;
            dataBeans.add(dataBean);
        }
        if (dataBeans.get(0).edtFlag){
            edtStr.set("完成");
        }else {
            edtStr.set("编辑");
        }
        carAdapter.setNewInstance(dataBeans);
    }

    //全选按钮点击监听
    public void checkAllListener(){
        //判断全选按钮是否可以点击
        List<CarEntity.DataBean> list = carAdapter.getData();
        if (list.size()==0)
            return;
        if (!list.get(0).edtFlag){
            showMsg("先点击编辑");
            Boolean flag = allCheck.get();
            allCheck.set(flag);
            return;
        }
        boolean allFlag = !allCheck.get();
        allCheck.set(allFlag);
        List<CarEntity.DataBean>dataBeans=new ArrayList<>(list);
        for (int i = 0; i < dataBeans.size(); i++) {
            dataBeans.get(i).selFalg=allFlag;
        }
        checkPrice();
        carAdapter.setNewInstance(dataBeans);
    }


    //去结算按钮生成订单
    public void orderListener(){
        List<CarEntity.DataBean> list = carAdapter.getData();
        if (list.size()==0){
            showMsg("购物车没有数据");
            return;
        }
        List<CarEntity.DataBean>goodsList = new ArrayList<>();
        for (CarEntity.DataBean value : list ){
            if (value.selFalg&&value.getGoods_count()>0){
                goodsList.add(value);
            }
        }
        int id = ((UserProvider) ARouter.getInstance().build("/usergroup/userprovider").navigation()).getUserId();
        if (id == 0){
            //跳转到登录界面
            Map<String,Object>pageMap = new HashMap<>();
            pageMap.put(UIField.ACTIONTYPE,UIField.AROUTERSTART);
            pageMap.put(UIField.ACTIONROUTERKEY,"/user/login");
            getUiChangeLiveData().getStartActivity().setValue(pageMap);
        }
        if (goodsList.size() == 0){
            //为选择任何商品
            ToastUtils.showShort("未选择要支付商品");
            return;
        }
        Map<String,Object>map = new HashMap<>();
        map.put("goodsList",goodsList);
        map.put("totalPrice",(long)price);
        map.put("userId",id);
        m.requestSubCar(map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this);
    }
    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        CarEntity.DataBean dataBean = (CarEntity.DataBean) adapter.getItem(position);
        if (!dataBean.edtFlag){
            showMsg("非编辑状态");
            return;
        }
        if (R.id.car_item_left==view.getId()){
            int goods_count = dataBean.getGoods_count();
            dataBean.setGoods_count(goods_count-1);
            if (dataBean.getGoods_count()<0){
                dataBean.setGoods_count(0);
            }
        }else if (R.id.car_item_right==view.getId()){
            int goods_count = dataBean.getGoods_count();
            dataBean.setGoods_count(goods_count+1);
        }else if (R.id.car_item_radio==view.getId()){
            dataBean.selFalg=!dataBean.selFalg;
        }
        adapter.setData(position,dataBean);
        checkPrice();
    }
}
